#pragma once
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
using namespace std;

const string path = "/home/myh/112";
const int projId = 0x6666;
// 操作系统申请空间，是按照块为单位的。
const int gsize = 4096;
const mode_t gmod = 0600; // 创建权限，为了挂接时有资格挂接

string ToHex(key_t k)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%x", k);
    return buffer;
}

class ShareMemory
{
private:
    void CreateShmple(int shmfig)
    {
        _key = ftok(path.c_str(), projId);
        if (_key < 0)
        {
            cout << "ftok error" << endl;
        }
        // cout << "key is :" << ToHex(key) << endl;
        //  创建共享内存&&获取
        //  注意：共享内存也有权限
        _shmid = shmget(_key, gsize, shmfig);
        if (_shmid < 0)
        {
            cout << "shmget error " << endl;
            return;
        }
    }

public:
    ShareMemory() {}
    ~ShareMemory() {}
    void CreateShm()
    {
        CreateShmple(IPC_CREAT | IPC_EXCL | gmod);
    }
    void GetShm()
    {
        CreateShmple(IPC_CREAT);
    }
    // 挂接:共享内存挂件到内存地址空间上(shmat)
    void AttachShm()
    {
        _rshmat = shmat(_shmid, nullptr, 0);
        if ((long long)_rshmat == -1)
        {
            cout << "shmat erorr " << endl;
        }
        cout << "attach done" << (long long)_rshmat << endl;
    }
    // 去关联:共享内存从内存地址空间上取出(shmdt:去关联)
    void DttachShm()
    {
        shmdt(_rshmat);
        cout << "dttach done" << (long long)_rshmat << endl;
    }
    // 删除共享空间
    void DelentShm()
    {
        int n = shmctl(_shmid, IPC_RMID, nullptr);
        cout << "delentshm " << n << endl;
    }
    void* GetAddr()
    {
        return _rshmat;
    }

private:
    int _shmid;
    key_t _key;
    void *_rshmat;
};

ShareMemory shm;


struct Image
{
    char status[32];
    char lasttime[48];
    char image[4000];
};